import { message } from "antd";
import { ArgsProps } from "antd/lib/message";
import config from "src/config";
export * from "./request";
export * from "./regExp";
export * from "./string";
export * from "./date";
export * from "./style";
import requestInstance from "./request";
import CryptoJS from "crypto-js";
import { RecordListItem } from "src/views/admin/AdminType";

export const request = requestInstance;
type ConfigContent = React.ReactNode;
type ConfigDuration = number | (() => void);
type JointContent = ConfigContent | ArgsProps;
type ConfigOnClose = () => void;

class Toast {
	constructor() {
		message.config({
			maxCount: 1,
		});
	}
	info = (content: JointContent, duration?: ConfigDuration, onClose?: ConfigOnClose) => {
		message.info(content, duration, onClose);
	};
	success = (content: JointContent, duration?: ConfigDuration, onClose?: ConfigOnClose) => {
		message.success(content, duration, onClose);
	};
	error = (content: JointContent, duration?: ConfigDuration, onClose?: ConfigOnClose) => {
		message.error(content, duration, onClose);
	};
	warning = (content: JointContent, duration?: ConfigDuration, onClose?: ConfigOnClose) => {
		message.warning(content, duration, onClose);
	};
	loading = (content: JointContent, duration?: ConfigDuration, onClose?: ConfigOnClose) => {
		message.loading(content, duration, onClose);
	};
	destroy = (messageKey?: React.Key) => message.destroy(messageKey);
}

export const toast = new Toast();

export const genLongerArray = <T = unknown>(length = 1, item: T) => {
	return Array.from({ length }, () => item);
};

export const getImageUrl = (url: string) => {
	return `${process.env.REACT_APP_BASEURL}${url}`;
};
export const asyncSleep = (delay: number) => {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve(true);
		}, delay);
	});
};
type ChatItem = Omit<RecordListItem, "timeStamp"> & { timeStamp?: number };
export const addChatItem = ({ adminId, linkId, content, type, avatar, timeStamp }: ChatItem) => {
	console.log({ adminId, linkId, content, type, avatar });
	//type为1表示发送，type为2表示接收
	if (adminId === undefined || linkId === undefined || content === undefined || type === undefined) return;
	const recordKey = config.CHATRECORDKEY + adminId;
	let record = localStorage.getItem(recordKey);
	let plaintext: ChatItem[] = [];
	if (record) {
		record = JSON.parse(record);
		plaintext = JSON.parse(CryptoJS.AES.decrypt(record || "", config.chatSecret).toString(CryptoJS.enc.Utf8)) || [];
		plaintext.push({
			adminId,
			linkId,
			content,
			type,
			avatar,
			timeStamp: timeStamp || Date.now(),
		});
		plaintext.sort((a, b) => (a.timeStamp || 0) - (b.timeStamp || 0));
	} else {
		plaintext = [
			{
				adminId,
				linkId,
				content,
				type,
				avatar,
				timeStamp: timeStamp || Date.now(),
			},
		];
	}
	const ciphertext = JSON.stringify(CryptoJS.AES.encrypt(JSON.stringify(plaintext), config.chatSecret).toString());
	localStorage.setItem(recordKey, ciphertext);
};
export const getChatRecords: ({
	adminId,
	linkId,
	page,
	pageSize,
}: {
	adminId?: string;
	linkId: string;
	page?: number;
	pageSize?: number;
}) => RecordListItem[] = ({ adminId, linkId, page = 1, pageSize = 10 }) => {
	if (!adminId) return [];
	const recordKey = config.CHATRECORDKEY + adminId;
	let record = localStorage.getItem(recordKey);
	let plaintext = [];
	if (record) {
		record = JSON.parse(record);
		plaintext = JSON.parse(CryptoJS.AES.decrypt(record || "", config.chatSecret).toString(CryptoJS.enc.Utf8)) || [];
	}
	
	plaintext = plaintext.filter((item: ChatItem) => item.adminId === adminId && item.linkId === linkId);
	const originalStartPoint = plaintext.length - page * pageSize;
	const startPoint = originalStartPoint < 0 ? 0 : originalStartPoint;
	const endPoint = originalStartPoint + pageSize < 0 ? 0 : originalStartPoint + pageSize;
	plaintext = plaintext.slice(startPoint, endPoint);
	return plaintext;
};
export const isValidKey = (key: string | number | symbol, object: object): key is keyof typeof object => {
	return key in object;
};
